package com.example.qzzm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.example.adapter.MyAdapter;
import com.example.application.QZApplication;
import com.example.constant.App;
import com.example.jx.FileUtils;
import com.example.jx.JsonUtils;
import com.example.net.Client;
import com.example.qzzm.R;
import com.example.qzzm.ActActivity.FirstTask;
import com.example.view.GifView;
import com.example.view.MPopWindow;
import com.example.view.MPopWindow.OnShowChangedListener;
import com.example.view.MyListView;
import com.example.vo.Act;
import com.example.vo.Message;
import com.example.window.WindowUtil;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

/**
 * 主界面的Activity
 * 
 * @author Administrator
 *
 */
public class MainActivity extends Activity implements OnClickListener {
	// 登录按钮
	private ImageView login;
	// 列表数据
	private List<Act> acts = new ArrayList<Act>();
	// 南京活动
	private LinearLayout ivAct;
	// 列表
	private MyListView mListView;
	// 城市
	private TextView tvCity;
	// 城市选择弹出框
	private MPopWindow mPopWindow;
	// 弹出框内容
	private View popContent;
	// 上下指示图标
	private ImageView ivChoose;
	// 城市选择按钮
	private CheckBox cbBj;// 北京
	private CheckBox cbSh;// 上海
	private CheckBox cbGz;// 广州
	private CheckBox cbNj;// 南京

	private List<CheckBox> cbs = new ArrayList<CheckBox>();
	// 加载中
	private GifView gvLoad;
	// Handler
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case 0:
				gvLoad.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
				mPopWindow.dismiss();
				break;
			case 1:
				mListView.setVisibility(View.VISIBLE);
				gvLoad.setVisibility(View.GONE);
				break;
			default:
				break;
			}

		}
	};
	public QZApplication application;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		application = (QZApplication) getApplication();

		initView();
		initListeners();
		readChache();
	
	}
	/**
	 * 读取缓存
	 */
	private void readChache() {
		Serializable serializable = FileUtils.readObjectFromChache("list_MainActivity_json");
		if(serializable != null){
			List<Act> temps = new ArrayList<Act>();
			temps = JsonUtils.paraseJson(serializable.toString(), Message.class).getLists();
			for (Act act : temps) {
				acts.add(act);
			}
			MyAdapter mAdapter = new MyAdapter(MainActivity.this, acts);
			mListView.setAdapter(mAdapter);
			handler.sendEmptyMessage(1);
		}else{
			FirstTask fTask = new FirstTask();
			fTask.execute(App.cityNo.get("南京"));
		}
	}
	// 只能选择一个
	private void selectCity(View cb) {
		for (CheckBox cbox : cbs) {
			if ((View) cbox != cb) {
				cbox.setChecked(false);
			} else {
				cbox.setChecked(true);
			}
		}
	}

	// 初始化布局控件
	private void initView() {
		mListView = (MyListView) findViewById(R.id.mlv_list);
		mListView.addHeader();
		mListView.setVisibility(View.GONE);
		login = (ImageView) findViewById(R.id.iv_write);
		ivAct = (LinearLayout) findViewById(R.id.ll_act);
		tvCity = (TextView) findViewById(R.id.tv_city);
		ivChoose = (ImageView) findViewById(R.id.iv_choose_city);
		gvLoad = (GifView) findViewById(R.id.gv_load);
		gvLoad.setMovieResource(R.raw.app_loading);
		gvLoad.setVisibility(View.GONE);
		mPopWindow = new MPopWindow(MainActivity.this);
		mPopWindow.setLayoutId(R.layout.index_popu);
		mPopWindow.setWindow(WindowUtil.getWidth(), WindowUtil.getHeigt());
		popContent = mPopWindow.getContentView();

		cbBj = (CheckBox) popContent.findViewById(R.id.cb_bj);
		cbGz = (CheckBox) popContent.findViewById(R.id.cb_gz);
		cbNj = (CheckBox) popContent.findViewById(R.id.cb_nj);
		cbSh = (CheckBox) popContent.findViewById(R.id.cb_sh);
		cbBj.setOnClickListener(this);
		cbGz.setOnClickListener(this);
		cbNj.setOnClickListener(this);
		cbSh.setOnClickListener(this);
		cbs.add(cbBj);
		cbs.add(cbGz);
		cbs.add(cbNj);
		cbs.add(cbSh);
		selectCity(cbNj);
	}

	// 初始化监听事件
	private void initListeners() {
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, LoginActivity.class));
			}
		});

		ivAct.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, ActActivity.class));
			}
		});

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, XQActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("itemId",
						acts.get((int)arg0.getAdapter().getItemId(arg2)).getAct_id());
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

		tvCity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPopWindow.setViewStartAnimationId(
						(LinearLayout) popContent.findViewById(R.id.ly_content),
						R.anim.fade_in);
				mPopWindow.showPopupWindow(tvCity);
			}
		});

		mPopWindow.setShowChangedListener(new OnShowChangedListener() {

			@Override
			public void onShowChanged(boolean isShowing) {
				// TODO Auto-generated method stub
				if (!isShowing) {
					ivChoose.setImageResource(R.drawable.main_icon5);
				} else {
					ivChoose.setImageResource(R.drawable.main_up);
				}
			}
		});
	}

	class FirstTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// 开始执行
			handler.sendEmptyMessage(0);
			// 网络访问，获取列表数据
			Client client = application.getClient();
			String result = client.getResquest(App.INDEX_URL + params[0]);
			if (result != null) {
				acts = JsonUtils.paraseJson(result, Message.class).getLists();
				//缓存第一页内容
				FileUtils.saveObjectToChache(result,"list_MainActivity_json");
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if (acts == null) {
				return;
			}// 执行成功
			MyAdapter mAdapter = new MyAdapter(MainActivity.this, acts);
			mListView.setAdapter(mAdapter);
			handler.sendEmptyMessage(1);
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// 更新
			super.onProgressUpdate(values);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		selectCity(v);
		String key = "南京";
		tvCity.setText("南京");
		if (v == cbBj) {
			key = "北京";
			tvCity.setText("北京");
		}
		if (v == cbGz) {
			key = "广州";
			tvCity.setText("广州");
		}
		if (v == cbSh) {
			key = "上海";
			tvCity.setText("上海");
		}
		application.setCity(key);
		FirstTask fTask = new FirstTask();
		fTask.execute(App.cityNo.get(key));
	}
}
